﻿using System;

namespace UnionnetClient.Model
{
	public class UnloginState : StateBase
	{
		public UnloginState(StateMachine stateMachine) : base(stateMachine)
		{
			//SettingsHelper.Settings.SettingsChanged += SettingsChanged;
		}

		public event EventHandler LoginTimeout;
		public event EventHandler LoginCompleted;

		public override void Login()
		{
			base.Login();

			lh = new LoginHelper();
			lh.LoginCompleted += lh_LoginCompleted;

			lh.LoginTimeout += delegate(object sender, EventArgs e) { OnLoginTimeout(); };

			ld = LoginData.Instance;
			lh.LoginAsync(ld);
		}

		public void CancelLogin()
		{
			if (lh != null)
			{
				lh.CancelLogin();
			}
		}

		protected virtual void OnLoginTimeout()
		{
			if (LoginTimeout != null)
			{
				LoginTimeout(this, EventArgs.Empty);
			}
		}

		protected virtual void OnLoginCompleted()
		{
			if (LoginCompleted != null)
			{
				LoginCompleted(this, EventArgs.Empty);
			}
		}

		protected delegate void ExceptionHandler(Exception ex);
		protected ExceptionHandler ProcessException;

		#region 私有

		private LoginHelper lh;
		private LoginData ld;

		private void lh_LoginCompleted(object sender, EventArgs e)
		{
			try
			{
				switch (lh.LoginState)
				{
					case LoginStateType.Successful:
						//状态切换
						if (ld.IsVPN) //vpn方式
						{
							stateMachine.SetState(stateMachine.VpnS);
							stateMachine.VpnS.StartTestNetwork();
						}
						else
						{
							stateMachine.NonVpnS.LoginHelperInstance = lh;
							stateMachine.SetState(stateMachine.NonVpnS);
							stateMachine.NonVpnS.StartTestNetwork();
						}

						if (lh.ServiceAddress != string.Empty)
						{
							AppEnvironment.Settings[SettingsProperty.ServiceAddress] = lh.ServiceAddress;
						}
						break;

					case LoginStateType.Repetition:
						stateMachine.SetState(stateMachine.UnknownLoginedS);
						stateMachine.UnknownLoginedS.StartTestNetwork();
						throw new InvalidOperationException("已经登陆，请勿重复登陆！");

					case LoginStateType.PasswordWrong:
						throw new InvalidOperationException("账户或密码错误！");

					case LoginStateType.Execption:
						throw new InvalidOperationException(lh.ExceptionMessage);

					default:
						throw new Exception(lh.LoginState.ToString());
				}
				OnLoginCompleted();
			}
			catch (Exception ex)
			{
				//throw ex;
				ProcessException(ex);
			}
		}

		//private void SettingsChanged(object sender, EventArgs e)
		//{
		//    if (lh.LoginState == LoginStateType.Logining)
		//    {
		//        throw new InvalidOperationException("当前正在登陆，不能更改设置！");
		//    }
		//}

		#endregion
	}
}
